package com.atguigu.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author sx
 * @date 2022-02-23 12:35
 */
@Controller
public class MyContorller {

    @RequestMapping({"/", "/index","index.html"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,SpringBoot_Shiro");
        return "index";
    }

    @RequestMapping({"/user/add"})
    public String add(){
        return "user/add";
    }

    @RequestMapping({"/user/update"})
    public String update(){
        return "user/update";
    }

    @RequestMapping({"/toLogin"})
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录信息
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        try {
            //执行登录的方法
            subject.login(token);
            return "index";
        } catch (UnknownAccountException uae) {
            // 没有指定用户，shiro 抛出UnknownAccountException
            System.out.println("==================>>>>>>>>>>>There is no user with username of " + token.getPrincipal());
            model.addAttribute("msg","用户名错误");
            return "login";
        } catch (IncorrectCredentialsException ice) {
            // 密码不对，shiro 抛出IncorrectCredentialsException
            System.out.println("==================>>>>>>>>>>>Password for account " + token.getPrincipal() + " was incorrect!");
            model.addAttribute("msg","密码错误");
            return "login";
        } catch (LockedAccountException lae) {
            // 用户被锁定。shiro抛出LockedAccountException
            System.out.println("==================>>>>>>>>>>>The account for username " + token.getPrincipal() + " is locked.Please contact your administrator to unlock it.");
            model.addAttribute("msg","当前用户已被锁定");
            return "login";
        } catch (AuthenticationException ae) {
            // 所有认证是异常的总类
            return "login";
        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unoauthorized(){
        return "未经授权无法访问此页面";
    }
}
